const router = require('koa-router')()
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { getList, getDetail, addBlog, updateBlog, delBlog } = require('../controller/blog')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')

router.get('/list', async (ctx, next) => {
  const author = ctx.query.author || ''
  const keyword = ctx.query.keyword || ''
  const result = getList(author, keyword)

  return result.then(data => {
    ctx.body = new SuccessModel(data)
  })
})

router.get('/detail', async (ctx, next) => {
  const id = ctx.query.id
  const result = getDetail(id)

  return result.then(data => {
    ctx.body = new SuccessModel(data)
  })
})

router.post('/add', loginCheck, async (ctx, next) => {
  ctx.request.body.author = 'haiyang'
  const result = addBlog(ctx.request.body)

  return result.then(data => {
    if (data) {
      ctx.body = new SuccessModel('新建博客成功')
    } else {
      ctx.body = new ErrorModel('新建博客失败!')
    }
  })
})

router.post('/update', loginCheck, async (ctx, next) => {
  const id = ctx.query.id
  const result = updateBlog(id, ctx.request.body)

  return result.then(data => {
    if (data) {
      ctx.body = new SuccessModel('修改博客成功')
    } else {
      ctx.body = new ErrorModel('修改博客失败!')
    }
  })
})

router.post('/del', loginCheck, async (ctx, next) => {
  const id = ctx.query.id
  const author = 'haiyang'

  const result = delBlog(id, author)
  return result.then(data => {
    if (data) {
      ctx.body = new SuccessModel('删除博客成功')
    } else {
      ctx.body = new ErrorModel('删除博客失败!')
    }
  })
})

module.exports = router